package com.example.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.gulimall.common.constant.ProductConstant;
import com.example.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.example.gulimall.product.entity.*;
import com.example.gulimall.product.service.AttrAttrgroupRelationService;
import com.example.gulimall.product.service.AttrGroupService;
import com.example.gulimall.product.service.CategoryService;
import com.example.gulimall.product.vo.AttrGroupRelationVo;
import com.example.gulimall.product.vo.AttrRespVo;
import com.example.gulimall.product.vo.AttrVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.gulimall.common.utils.PageUtils;
import com.example.gulimall.common.utils.Query;

import com.example.gulimall.product.dao.AttrDao;
import com.example.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


/**
 * @author xiehaidong
 */
@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private AttrGroupService attrGroupService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, String attrType,Long catelogId) {
        QueryWrapper<AttrEntity> attrEntityQueryWrapper = new QueryWrapper<>();
        attrEntityQueryWrapper.lambda().eq(AttrEntity::getAttrType,"base".equalsIgnoreCase(attrType)?ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode():ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        if(catelogId!=0){
            attrEntityQueryWrapper.lambda().eq(AttrEntity::getCatelogId,catelogId);
        }
       String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            attrEntityQueryWrapper.lambda().eq(AttrEntity::getAttrId,key).or().like(AttrEntity::getAttrName,key);
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), attrEntityQueryWrapper);

        PageUtils pageUtils = new PageUtils(page);
        //获取新增属性
        List<AttrEntity> records = page.getRecords();
        List<AttrRespVo>attrRespVoList = records.stream().map((attrEntity -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity,attrRespVo);
            CategoryEntity category = categoryService.getOne(new LambdaQueryWrapper<CategoryEntity>().eq(CategoryEntity::getCatId,attrRespVo.getCatelogId()));
            //获取分类名称
            if (category != null) {
                attrRespVo.setCatelogName(category.getName());
            }
            //获取分组名称
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity= attrAttrgroupRelationService.getOne(new LambdaQueryWrapper<AttrAttrgroupRelationEntity>().eq(AttrAttrgroupRelationEntity::getAttrId, attrRespVo.getAttrId()));
            if(attrAttrgroupRelationEntity!=null){
                AttrGroupEntity attrGroup = attrGroupService.getOne(new LambdaQueryWrapper<AttrGroupEntity>().eq(AttrGroupEntity::getAttrGroupId, attrAttrgroupRelationEntity.getAttrGroupId()));
                if(attrGroup!=null){
                    attrRespVo.setGroupName(attrGroup.getAttrGroupName());
                }
            }
            return attrRespVo;
        })).collect(Collectors.toList());
        //将新数据传递过去
        pageUtils.setList(attrRespVoList);
        return pageUtils;
    }
    @Override
    public void saveAttr(AttrVo attrVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attrEntity);
        this.save(attrEntity);
        //如果是规格参数，再操作分组信息
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode())
        {
            //保存规格型号参数与组号关系
        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
        attrAttrgroupRelationEntity.setAttrGroupId(attrVo.getAttrGroupId());
        attrAttrgroupRelationEntity.setAttrId(attrVo.getAttrId());
       attrAttrgroupRelationService.save(attrAttrgroupRelationEntity);}
    }

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrRespVo attrRespVo = new AttrRespVo();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity,attrRespVo);
        //如果是规格参数，再操作分组信息
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity attrAttrgroupRelation = attrAttrgroupRelationService.getOne(new LambdaQueryWrapper<AttrAttrgroupRelationEntity>().eq(AttrAttrgroupRelationEntity::getAttrId, attrId));
            if (attrAttrgroupRelation != null) {
                attrRespVo.setAttrGroupId(attrAttrgroupRelation.getAttrGroupId());
            }
            Long[] catelogPath = categoryService.findCatelogPath(attrEntity.getCatelogId());
            attrRespVo.setCatelogPath(catelogPath);
        }
        return attrRespVo;
    }

    @Override
    @Transactional
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);
        //如果是规格参数，再操作分组信息
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode())
        {

            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
        attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
        attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
        int count= (int) attrAttrgroupRelationService.count(new LambdaQueryWrapper<AttrAttrgroupRelationEntity>().eq(AttrAttrgroupRelationEntity::getAttrId,attrAttrgroupRelationEntity.getAttrId()));
        if(count==0){
            //插入数据
            attrAttrgroupRelationService.save(attrAttrgroupRelationEntity);
        }
        else {
            //更新数据
            attrAttrgroupRelationService.update(attrAttrgroupRelationEntity,new LambdaQueryWrapper<AttrAttrgroupRelationEntity>().eq(AttrAttrgroupRelationEntity::getAttrId,attrAttrgroupRelationEntity.getAttrId()));
        }
    }
    }

    @Override
    public List<AttrEntity> getRelationAttr(long attrGroupId) {
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntityList = attrAttrgroupRelationService.list(new LambdaQueryWrapper<AttrAttrgroupRelationEntity>().eq(AttrAttrgroupRelationEntity::getAttrGroupId, attrGroupId));
        List<Long> attrIds = attrAttrgroupRelationEntityList.stream().map((entity -> {
            return entity.getAttrId();
        })).collect(Collectors.toList());
        List<AttrEntity> attrEntities = this.baseMapper.selectBatchIds(attrIds);
        return attrEntities;
    }

    @Override
    public PageUtils getNoAttrRelation(long attrGroupId,Map<String, Object> params) {
       //1当前分组只能关联自己所属分类里面的所有属性
        //查询当前分组属于分类
        LambdaQueryWrapper<AttrGroupEntity> attrGroupEntityLambdaQueryWrapper = new LambdaQueryWrapper<AttrGroupEntity>().eq(AttrGroupEntity::getAttrGroupId, attrGroupId);
        AttrGroupEntity attrGroup = attrGroupService.getOne(attrGroupEntityLambdaQueryWrapper);
        Long catelogId = attrGroup.getCatelogId();
        //2当前分组只能关联别的分组没有引用的属性
        //2.1查询当前分类下所有分组
        List<AttrGroupEntity> attrGroupEntityList= attrGroupService.list(new LambdaQueryWrapper<AttrGroupEntity>().eq(AttrGroupEntity::getCatelogId, catelogId));
        List<Long> attrGroupIds = attrGroupEntityList.stream().map((attrGroup1 -> {
            return attrGroup1.getAttrGroupId();
        })).collect(Collectors.toList());
        //2.2这些分组关联的属性
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntityList = attrAttrgroupRelationService.list(new LambdaQueryWrapper<AttrAttrgroupRelationEntity>().in(AttrAttrgroupRelationEntity::getAttrGroupId, attrGroupIds));
        List<Long> attrIds = attrAttrgroupRelationEntityList.stream().map((attrAttrgroupRelationEntity -> {
            return attrAttrgroupRelationEntity.getAttrId();
        })).collect(Collectors.toList());
        //从当前分类的所有属性中移除这些属性
        LambdaQueryWrapper<AttrEntity> attrEntityLambdaQueryWrapper= new LambdaQueryWrapper<AttrEntity>().eq(AttrEntity::getCatelogId, catelogId).eq(AttrEntity::getAttrType, ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if(attrIds!=null&&attrIds.size()>0){
            attrEntityLambdaQueryWrapper.notIn(AttrEntity::getAttrId,attrIds);
        }
       //模糊查询
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
attrEntityLambdaQueryWrapper.eq(AttrEntity::getAttrId,key).or().like(AttrEntity::getAttrName,key);
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), attrEntityLambdaQueryWrapper);
        return new PageUtils(page);

    }


    @Override
    public void deleteRelation(AttrGroupRelationVo[] attrGroupRelationVo) {
        List<AttrGroupRelationVo> attrGroupRelationVoList = Arrays.asList(attrGroupRelationVo);
        for (AttrGroupRelationVo Vo : attrGroupRelationVoList) {
            LambdaQueryWrapper<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntityLambdaQueryWrapper = new LambdaQueryWrapper<AttrAttrgroupRelationEntity>().eq(AttrAttrgroupRelationEntity::getAttrId, Vo.getAttrId()).eq(AttrAttrgroupRelationEntity::getAttrGroupId, Vo.getAttrGroupId());
            attrAttrgroupRelationService.remove(attrAttrgroupRelationEntityLambdaQueryWrapper);
        }

    }


}
